use std::{
    marker::PhantomData,
    ops::Deref,
    ptr::NonNull,
    sync::atomic::{self, AtomicUsize, Ordering::Release},
};
struct Arc<T> {
    // NonNull 协变的原理：mut不可变，但是const可变。虽然声明里const，但是数据本身是mut，所以仍然可以强转回mut
    ptr: NonNull<ArcInner<T>>,
    phantom: PhantomData<ArcInner<T>>,
}
struct ArcInner<T> {
    rc: AtomicUsize,
    data: T,
}

impl<T> Arc<T> {
    pub fn new(data: T) -> Self {
        let arc = ArcInner {
            rc: AtomicUsize::new(1),
            data,
        };
        let arc = Box::new(arc);
        let arc = Box::into_raw(arc);
        Arc {
            ptr: NonNull::new(arc).unwrap(),
            phantom: PhantomData,
        }
    }
}
impl<T> Deref for Arc<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        let inner = unsafe { self.ptr.as_ref() };
        &inner.data
    }
}
impl<T> Clone for Arc<T> {
    fn clone(&self) -> Self {
        let ptr = unsafe { self.ptr.as_ref() };
        let old_rc = ptr.rc.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        if old_rc > isize::MAX as usize {
            std::process::abort();
        }
        Self {
            ptr: self.ptr.clone(),
            phantom: PhantomData,
        }
    }
}
impl<T> Drop for Arc<T> {
    fn drop(&mut self) {
        let inner = unsafe { self.ptr.as_ref() };
        // release 防止前面的指令被重排到销毁步骤，if 块是将整个指令作为一个整体
        if inner.rc.fetch_sub(1, Release) != 1 {
            return;
        }
        // acquire 防止之后的指令被重排到前面
        atomic::fence(atomic::Ordering::Acquire);
        unsafe {
            Box::from_raw(self.ptr.as_ptr());
        }
    }
}
// T同时限定两个特征是为了线程安全。多拥有者没有Sync则必然存在data race，
// 跨线程传递必然需要Send
unsafe impl<T: Send + Sync> Send for Arc<T> {}
unsafe impl<T: Send + Sync> Sync for Arc<T> {}
